package com.wn.framework.manager

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper

/**
 * @Author: wn
 * @Date: 2024/8/13 15:59
 * @Description: Activity管理类
 */
object ActivityManager {
  private val tasks = mutableListOf<Activity>()

  /**
   * 添加 Activity 到 list 中
   * @param activity Activity
   */
  fun push(activity: Activity) {
    tasks.add(activity)
  }

  /**
   * list 移除 Activity
   * @param activity Activity
   */
  fun pop(activity: Activity) {
    tasks.remove(activity)
  }

  fun top(): Activity {
    return tasks.last()
  }

  /**
   * Activity是否销毁 -- 销毁 true
   * @param context Context
   * @return Boolean
   */
  fun isActivityDestroy(context: Context): Boolean {
    val activity = findActivity(context)
    return activity?.run {
      isDestroyed || isFinishing
    } ?: true
  }

  /**
   * ContextWrapper是context的包装类，AppcompatActivity，service，application实际上都是ContextWrapper的子类
   * @param context Context
   * @return Activity?
   */
  private fun findActivity(context: Context): Activity? = when (context) {
    // 怎么判断context是不是Activity
    is Activity -> context // 这种方法不够严谨
    is ContextWrapper -> findActivity(context.baseContext)
    else -> null
  }

  fun finishAllActivity(callback: (() -> Unit)? = null) {
    val it = tasks.iterator()
    while (it.hasNext()) {
      val item = it.next()
      it.remove()
      item.finish()
    }
    callback?.invoke()
  }

  /**
   * 关闭其他activity
   */
  fun finishOtherActivity(clazz: Class<out Activity>) {
    val it = tasks.iterator()
    while (it.hasNext()) {
      val item = it.next()
      if (item::class.java != clazz) {
        it.remove()
        item.finish()
      }
    }
  }


  /**
   * 关闭activity
   */
  fun finishActivity(clazz: Class<out Activity>) {
    val it = tasks.iterator()
    while (it.hasNext()) {
      val item = it.next()
      if (item::class.java == clazz) {
        it.remove()
        item.finish()
        break
      }
    }
  }

  /**
   * activity是否在栈中
   */
  fun isActivityExistsInStack(clazz: Class<out Activity>?): Boolean {
    if (clazz != null) {
      for (task in tasks) {
        if (task::class.java == clazz) {
          return true
        }
      }
    }
    return false
  }
}